package com.iwhalecloud.uncc.utils;

import com.iwhalecloud.uncc.common.ArchiverConstant;
import com.iwhalecloud.uncc.db.DatasourceContextHolder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author zq
 * @date 2021/10/19 17:34
 * @description PartitionUtil
 */
@Component
public class HisUtil {

    /**
     * 2 的 次方数
     */
    private static int  historyNum;

    public static Integer getHisNum(String code){
        return Integer.parseInt(code)&(historyNum-1);
    }

    public static String getPartitionCode(String code){
        return ArchiverConstant.HISTORY_PARTITION_CODE_PREFIX + getHisNum(code);
    }

    public static String changeHisDatasource(String oldPartitionCode) {
        if (oldPartitionCode != null) {
            DatasourceContextHolder.setDs(ArchiverConstant.HIS + getHisNum(oldPartitionCode));
        } else {
            DatasourceContextHolder.setDs(ArchiverConstant.DB_DEFAULT_HIS);
        }
        return getPartitionCode(oldPartitionCode);
    }



    @Value("${archiver.dbNumber.history}")
    public void setHistoryNum(int historyNum) {
        HisUtil.historyNum = historyNum;
    }
}
